from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


URL = "https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver"

# locators
CHANGE_TEXT_BUTTON = ("id", "populate-text")
H2_TEXT = ("id", "h2")
DISPLAY_BUTTON = ("id", "display-other-button")
ENABLE_HIDE_BUTTON = ("id", "hidden")
ENABLE_BUTTON = ("id", "enable-button")
DISABLE_BUTTON = ("id", "disable")
CLICK_BUTTON = ("id", "alert")


class Page:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 15, poll_frequency=1)

    def click_button(self, element_locator):
        self.driver.find_element(*element_locator).click()

    def wait_text(self, locator, text):
        self.wait.until(EC.text_to_be_present_in_element(locator, text))

    def wait_element(self, locator):
        self.wait.until(EC.visibility_of_element_located(locator))

    def wait_click_element(self, locator):
        self.wait.until(EC.element_to_be_clickable(locator))

    def wait_alert_and_click(self):
        self.wait.until(EC.alert_is_present())
        alert = self.driver.switch_to.alert
        alert.accept()

    def check_text(self, locator):
        return self.driver.find_element(*locator).text

    def is_element_enabled(self, locator):
        return self.driver.find_element(*locator).is_enabled()


def setup():
    options = webdriver.ChromeOptions()
    options.add_argument("--window-size=1920,1080")
    driver = webdriver.Chrome(options=options)
    driver.get(URL)
    return Page(driver)


def click_change_text_to_selenium_webdriver(page):
    page.click_button(CHANGE_TEXT_BUTTON)
    page.wait_text(H2_TEXT, "Selenium Webdriver")

    assert page.check_text(H2_TEXT) == "Selenium Webdriver"


def click_display_button_after_10_seconds(page):
    page.click_button(DISPLAY_BUTTON)
    page.wait_element(ENABLE_HIDE_BUTTON)

    assert page.check_text(ENABLE_HIDE_BUTTON) == "Enabled"


def click_enable_button_after_10_seconds(page):
    page.click_button(ENABLE_BUTTON)
    page.wait_click_element(DISABLE_BUTTON)

    assert page.is_element_enabled(DISABLE_BUTTON)


def click_me_to_open_an_alert_after_5_seconds(page):
    page.click_button(CLICK_BUTTON)
    page.wait_alert_and_click()


if __name__ == "__main__":
    page = setup()

    click_change_text_to_selenium_webdriver(page)
    click_display_button_after_10_seconds(page)
    click_enable_button_after_10_seconds(page)
    click_me_to_open_an_alert_after_5_seconds(page)
